package cool.taomu.toolkit.service.client.kademlia.service

import com.google.inject.Inject
import cool.taomu.toolkit.service.client.kademlia.utils.ServiceClientPool
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.service.KRoutingTable
import cool.taomu.toolkit.service.kademlia.thrift.KademliaService
import cool.taomu.toolkit.service.kademlia.thrift.ServiceEntity
import cool.taomu.toolkit.utils.ByteBufferUtils
import java.nio.charset.StandardCharsets
import java.util.List
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.transport.layered.TFramedTransport
import org.slf4j.LoggerFactory
import com.google.common.base.Optional

class FindServiceImpl {

    val static LOG = LoggerFactory.getLogger(FindServiceImpl);

    @Inject
    ServiceClientPool clientPool;

    @Inject
    KRoutingTable router;

    def synchronized getServiceNodes(KPeerNode peer, ServiceEntity message, List<String> excludeIds) {
        LOG.info("****K桶中节点数量:{}****", this.router.ksize)
        var opt = clientPool.peerClient(peer, router.localNode, [ client |
            if (client !== null) {
                var resp = client.findServiceNode(message, excludeIds)
                // var data = ByteBufferUtils.toString(resp.data, StandardCharsets.UTF_8)
                if (resp.status == 200) {
                    LOG.info("find service node:{}", resp)
                    return resp;
                }
            }
            return null
        ])
        return opt
    }

    def synchronized callService(KPeerNode peer, ServiceEntity message) {
        LOG.info("****K桶中节点数量:{}****", this.router.ksize)
        var opt = clientPool.peerClient(peer, router.localNode, [ client |
            if (client !== null) {
                var resp = client.findService(message)
                // var data = ByteBufferUtils.toString(resp.data, StandardCharsets.UTF_8)
                if (resp.status == 200) {
                    LOG.info("find service node:{}", resp)
                    return resp;
                }
            }
            return null
        ])
        return opt
    }
}
